package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustomException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import com.heima.utils.common.IdCardUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author zhanghao
 * @date 2021/4/12 16:13
 */
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //1.参数检查
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //2.条件查询
        Page<ApUserRealname> pageReq = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> queryWrapper = Wrappers.<ApUserRealname>lambdaQuery();
        if (dto.getStatus() != null) {
            queryWrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage<ApUserRealname> resultPage = page(pageReq, queryWrapper);
        //  3.返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) resultPage.getTotal());
        pageResponseResult.setData(resultPage.getRecords());
        return pageResponseResult;
    }

    @Resource
    ApUserMapper apUserMapper;

    @Override
    @GlobalTransactional
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        //1.检查参数
        if (dto == null || dto.getId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID, "实名认证id不存在");
        }
        //2.根据id查询实名认证信息
        ApUserRealname userRealname = getById(dto.getId());
        //3.判断实名认证状态是否为待审核
        if (userRealname == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "实名认证数据不存在");
        }
        if (userRealname.getStatus() != 1) {
            throw new CustomException(AppHttpCodeEnum.DATA_STATUS_ERROR, "实名认证状态错误");
        }
        //4.查询实名认证用户关联的ap_user 信息
        ApUser apUser = apUserMapper.selectById(userRealname.getUserId());
        if (apUser == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_STATUS_ERROR, "关联的app用户信息不存在");
        }
        //5.更新实名认证信息
        userRealname.setStatus(status);
        userRealname.setCreatedTime(new Date());
        if (StringUtils.isNotBlank(dto.getMsg())) {
            userRealname.setReason(dto.getMsg());
        }
        updateById(userRealname);
        //6.如果审核信息为9 则创建自媒体账号和作者信息
        if (status.intValue() == AdminConstants.AD_USER_ISSTATUS) {
            //基于apuser创建wmuser
            WmUser wmUser = createWmUser(apUser);
            if (wmUser == null) {
                throw new CustomException(AppHttpCodeEnum.SERVER_ERROR, "自媒体用户创建失败");
            }
            //创建作者信息
            ResponseResult result = createAuthor(apUser, wmUser);
            if (result.getCode() != 0) {
                throw new CustomException(AppHttpCodeEnum.SERVER_ERROR, "作者信息创建失败");
            }
        }
        //7.修改ap_user的flag, 当前用户为自媒体人，返回信息
        apUser.setFlag((short) 1);
        apUserMapper.updateById(apUser);

        //if (!IdCardUtils.checkIdCardInfo(userRealname.getName(), userRealname.getIdno())) {
        //    throw new CustomException(AppHttpCodeEnum.PARAM_INVALID, "姓名和身份证号认证不通过");
        //}
        //System.out.println(1/0); // 制造异常
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    ArticleFeign articleFeign;

    private ResponseResult createAuthor(ApUser apUser, WmUser wmUser) {
        //根据apuser查询对应的作者信息是否存在
        ApAuthor author = articleFeign.findByUserId(apUser.getId());
        if (author != null) {
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST, "对应的作者已经存在");
        }
        author = new ApAuthor();
        author.setName(apUser.getName());
        author.setType(2);
        author.setUserId(apUser.getId());
        author.setCreatedTime(new Date());
        author.setWmUserId(wmUser.getId());
        return articleFeign.save(author);
    }

    @Autowired
    WemediaFeign wemediaFeign;

    private WmUser createWmUser(ApUser apUser) {
        //根据用户查询对应的自媒体是否存在
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());
        if (wmUser != null) {
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST, "对应的自媒体用户已经存在");
        }
        wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
        return wemediaFeign.save(wmUser);
    }
}
